
import os
from zhipuai import ZhipuAI

# 初始化客户端
client = ZhipuAI(api_key="")  # 替换为实际API密钥

def sync_request():
    """同步请求示例"""
    response = client.chat.completions.create(
        model="glm-4",
        messages=[{"role": "user", "content": "讲个笑话"}],
        top_p=0.7,
        temperature=0.9,
        max_tokens=2000,
        stream=False
    )
    print(response.choices[0].message.content)

def stream_request():
    """流式请求示例"""
    response = client.chat.completions.create(
        model="glm-4",
        messages=[{"role": "user", "content": "介绍Python语言"}],
        top_p=0.7,
        temperature=0.9,
        stream=True,
        max_tokens=2000
    )
    for chunk in response:
        content = chunk.choices[0].delta.content
        print(content, end='', flush=True)

if __name__ == "__main__":
    print("=== 同步请求 ===")
    sync_request()
    
    print("\n=== 流式请求 ===")
    stream_request()
